<template>
  <section class="todoapp">
    <TdHerder @todoAdd="todoAdd"></TdHerder>
    <TdBody
      @changeAll="changeAll"
      :list="typeList"
      @checkBtn="checkBtn"
      @del="del"
    ></TdBody>
    <TdFooter
      :sum="sum"
      :clearBtn="clearBtn"
      :type="type"
      @delAll="delAll"
      @tabqiehuan="tabqiehuan"
    ></TdFooter>
  </section>
</template>

<script>
import TdHerder from './components/TdHeader.vue'
import TdBody from './components/TdBody.vue'
import TdFooter from './components/TdFooter.vue'
export default {
  components: {
    TdHerder,
    TdBody,
    TdFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        {
          id: 1,
          value: '机械师',
          flag: false,
        },
        {
          id: 2,
          value: '格斗家',
          flag: true,
        },
        {
          id: 3,
          value: '剑豪',
          flag: false,
        },
      ],
      type: 'all',
    }
  },
  methods: {
    // 类名切换
    checkBtn(id, flag) {
      // console.log(id, value)
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = flag
        }
      })
    },

    //添加
    todoAdd(name) {
      this.list = [
        ...this.list,
        {
          id: +new Date(),
          value: name,
          flag: false,
        },
      ]
    },

    // 删除
    del(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },

    // 删除完成
    delAll() {
      this.list = this.list.filter((item) => !item.flag)
    },

    // 修改所有事件状态
    changeAll(flag) {
      this.list.forEach((item) => (item.flag = flag))
    },

    // tab切换筛选
    tabqiehuan(type) {
      console.log(type)
      this.type = type
    },
  },
  computed: {
    // 剩余
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    clearBtn() {
      return this.list.some((item) => !item.flag)
    },
    typeList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  // 本地存储
  watch: {
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem('list', JSON.stringify(newVal))
      },
    },
  },
}
</script>

<style></style>
